import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

///
///Create by gjh on 2022/1/21
///
class HanziWidget extends StatefulWidget {

  final double size;
  final String hanzi;


  HanziWidget({this.size=100, this.hanzi="汉"});

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return HanziState();
  }
}

class HanziState extends State<HanziWidget>{

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _copyDbFileToCacheDocument();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      width: widget.size,
      height: widget.size,
      child: CustomPaint(
        painter: HanziPaintr(),
      ),
    );
  }

  //将flutter路径下的db文件,copy到android/ios的 缓存目录下
  _copyDbFileToCacheDocument() async {
    var databasesPath = await getDatabasesPath();
    var path = join(databasesPath, 'hanzi.db');

    // delete existing if any
    await deleteDatabase(path);

    // Make sure the parent directory exists
    try {
      await Directory(dirname(path)).create(recursive: true);
    } catch (_) {}

    // Copy from asset
    // var data = await rootBundle.load(join('assets/dbfile/hanzi.db'));
    var data = await rootBundle.load(join('assets', 'hanzi.db'));

    List<int> bytes =
    data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
    // Write and flush the bytes written
    await File(path).writeAsBytes(bytes, flush: true);

    //从缓存目录读取db文件里面的数据
    queryData();
  }

  //从缓存目录读取db文件里面的数据
  queryData() async {
    var databasesPath = await getDatabasesPath();
    var path = join(databasesPath, 'hanzi.db');
    // open the database
    var db = await openDatabase(path);

    // Our database as a single table with a single element
    var data = await db.rawQuery('SELECT * FROM hzdb WHERE text="${widget.hanzi}"');
    print('data $data');
    // setState(() {});

    await db.close();
  }


  openJsonFile() async{
    var data = await rootBundle.load(join('assets', 'hanzi.db'));
    print("--->data:$data");
  }
}

class HanziPaintr extends CustomPainter{

  @override
  void paint(Canvas canvas, Size size) {
    // TODO: implement paint
    // Path path = new Path();
    // path.moveTo(x, y)
    // canvas.drawPath(path, paint)
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return true;
  }

}